import { onMounted, ref } from "vue";
import { onBeforeRouteLeave } from "vue-router";

export default function (root: string, max: number, fps = 24) {
    const currentFrame = ref(root + 0 + ".png");
    let index = 0;
    let animation: number | null = null;
    const frameInterval = 1000 / fps;
    let lastTimestamp = 0;

    const render = (timestamp: number) => {
        if (!lastTimestamp) lastTimestamp = timestamp;

        const elapsed = timestamp - lastTimestamp;

        if (elapsed >= frameInterval) {
            index > max ? (index = 0) : index;
            currentFrame.value = root + index + ".png";
            index++;
            lastTimestamp = timestamp;
        }

        animation = requestAnimationFrame(render);
    };

    onMounted(() => {
        animation = requestAnimationFrame(render);
    });

    onBeforeRouteLeave(() => {
        if (animation !== null) {
            cancelAnimationFrame(animation);
        }
    });

    return {
        currentFrame
    };
}